package com.by.controller.sys;

import com.by.entity.sys.LoginBean;
import com.by.entity.sys.ModifyUser;
import com.by.entity.sys.User;
import com.by.common.bean.PageBean;
import com.by.common.bean.ResultBean;
import com.by.controller.BaseController;
import com.by.service.sys.UserService;
import com.by.token.TokenTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/user")
public class UserController extends BaseController {

    @Autowired
    UserService userService;

    @Autowired(required = false)
    TokenTemplate tokenTemplate;

    @GetMapping("/check")
    public ResultBean checkUser(String username) {
        int rs = userService.checkuser(username);
        return success("检查用户名是否可用", rs == 0 ? "yes" : "no");
    }

    @PostMapping("/save")
    public ResultBean save(@RequestBody @Validated User user, BindingResult result) {
        //后台验证
        Map validateMap = validate(result);
        if (null != validateMap) {//说明验证未通过
            return fail("验证失败", validateMap);
        }
        int rs = userService.save(user);
        if (rs == 1) {
            return success("保存成功");
        } else if (rs == 2) {
            fail("保存失败,用户名已存在！");
        }
        return fail("保存失败");
    }

    @PostMapping("/query")
    public ResultBean query(@RequestBody Map map) {
        PageBean bean = userService.query(map);
        return success("用户分页结果", bean);
    }

    @DeleteMapping("/delete")
    public ResultBean delete(String id) {
        int rs = userService.delete(id);
        return rs == 1 ? success("删除成功") : fail("删除失败");
    }

    @PutMapping("/update")
    public ResultBean update(@RequestBody User user) {
        int rs = userService.update(user);
        return rs == 1 ? success("修改成功") : fail("修改失败");
    }

    @PostMapping("/login")
    public ResultBean login(@RequestBody LoginBean loginBean, BindingResult result) {
        Map validate = validate(result);
        if (null != validate) {
            return fail("验证失败", validate);
        }

        User user = userService.queryUser(loginBean.getAccount());
        if (null == user) {
            return fail("账号不存在");
        }

        //对用户输入的密码加密
        String tmp = DigestUtils.md5DigestAsHex(loginBean.getPassword().getBytes());
        //判断密码是否正确
        if (!tmp.equals(user.getPassword())) {
            return fail("密码不正确！");
        }

        //判断账号状态
        if (user.isIslock()) {
            return fail("账号已锁定，请联系管理员！");
        }
        //取消密码
        user.setPassword(null);
        Map map = new HashMap();
        map.put("id", user.getId());
        map.put("account", user.getAccount());
        map.put("roleId", user.getRoleId());
        map.put("effectiveDate", user.getEffectiveDate());
        String token = tokenTemplate.generateToken(map);
        user.setToken(token);
        return success("登录成功", user);

    }

    @PostMapping("/modifypwd")
    public ResultBean modifypwd(@RequestBody ModifyUser user, BindingResult result) {
        Map map = validate(result);
        if (null != map) {
            return fail("验证失败", map);
        }
        //判断两次密码是否一致
        if (!user.getNewpwd().equals(user.getConfirmpwd()))
            return fail("两次密码输入不一致！");
        //查询用户的密码
        User tmp = userService.queryUserById(user.getId());
        //加密旧密码
        String pwd = DigestUtils.md5DigestAsHex(user.getOldpwd().getBytes());
        if (!pwd.equals(tmp.getPassword()))
            return fail("修改失败，旧密码不正确！");
        int rs = userService.updatePwd(user);
        return rs == 1 ? success("修改成功") : fail("修改失败");
    }
}
